/**
 * Copyright &copy; 2012-2015 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.soccer.cms.modules.cms.web;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.soccer.cms.common.config.Global;
import com.soccer.cms.common.persistence.Page;
import com.soccer.cms.common.web.BaseController;
import com.soccer.cms.common.utils.DBSquence;
import com.soccer.cms.common.utils.Encodes;
import com.soccer.cms.common.utils.StringUtils;
import com.soccer.cms.modules.cms.entity.Category;
import com.soccer.cms.modules.cms.entity.Imageinfo;
import com.soccer.cms.modules.cms.entity.Recommen;
import com.soccer.cms.modules.cms.service.RecommenService;
import com.soccer.cms.modules.cms.utils.RecommenUtils;
import com.soccer.cms.modules.sys.entity.Dict;
import com.soccer.cms.modules.sys.utils.DictUtils;

/**
 * 推荐功能Controller
 * @author zouqh
 * @version 2015-05-28
 */
@SuppressWarnings("unused")
@Controller
@RequestMapping(value = "${adminPath}/cms/recommen")
public class RecommenController extends BaseController {

	@Autowired
	private RecommenService recommenService;
	
	@ModelAttribute
	public Recommen get(@RequestParam(required=false) String id) {
		Recommen entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = recommenService.get(id);
		}
		if (entity == null){
			entity = new Recommen();
		}
		return entity;
	}
	
	@RequiresPermissions("cms:recommen:view")
	@RequestMapping(value = {"index"})
	public String indexPage(Recommen recommen, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		return "modules/cms/recommen/recommenIndex";
	}
	
	@RequiresPermissions("cms:recommen:view")
	@RequestMapping(value = {"list", ""})
	public String list(Recommen recommen, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		recommen.getGroupTypeList().add("0");
		recommen.getGroupTypeList().add("1");
		
		Page<Recommen> page = recommenService.findPage(new Page<Recommen>(request, response), recommen); 
		model.addAttribute("page", page);
		return "modules/cms/recommen/recommenList";
	}

	@RequiresPermissions("cms:recommen:view")
	@RequestMapping(value = "form")
	public String form(Recommen recommen, Model model) {
		if(recommen == null){
			recommen = new Recommen();
		}
		if(recommen.getImageinfoList().size()==0){
			List<Dict> dicts = DictUtils.getDictList("imagetype");
			for (Dict dict : dicts) {
				Imageinfo imageinfo = new Imageinfo();
				Dict dict1 = new Dict();
				dict1.setId(dict.getValue());
				imageinfo.setImagetype(dict1);
				recommen.getImageinfoList().add(imageinfo);
			}
		}
		
		model.addAttribute("recommen", recommen);
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		model.addAttribute("opt",request.getParameter("opt"));
		return "modules/cms/recommen/recommenForm";
	}

	@RequiresPermissions("cms:recommen:view")
	@RequestMapping(value = "formGroup")
	public String formGroup(Recommen recommen, Model model) {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		String displayType = request.getParameter("displaytype.id"); //显示类型
		String rootPage = "modules/cms/recommen/";
		Dict grouptype = new Dict();
		String groupTypeId = "0";
		String resturnPage = null;
		if(recommen == null){
			recommen = new Recommen();
		}
		
		//设置跳转页面 图片类型 0 简图; 1 小图 ; 2 大图
		if("1".equals(displayType)){ //轮播图
			resturnPage = rootPage+"recommenFormGroup";
			groupTypeId = "1";
		}else if("2".equals(displayType)){  //赛事
			resturnPage = rootPage+"recommenForm";
		}else if("3-1".equals(displayType)){//新闻1（大图）
			resturnPage = rootPage+"recommenFormNews";
			RecommenUtils.setRecommenImageInfo(recommen, "2");
		}else if("3-2".equals(displayType)){ //新闻2（小图）
			resturnPage = rootPage+"recommenFormNews";
			RecommenUtils.setRecommenImageInfo(recommen, "1");
		}else if("4-1".equals(displayType)){  //视频类型1（大图）
			resturnPage = rootPage+"recommenFormVideo";
			RecommenUtils.setRecommenImageInfo(recommen, "2");
		}else if("4-2".equals(displayType)){ //视频类型2（小图）
			resturnPage = rootPage+"recommenFormVideoGroup";
			RecommenUtils.setRecommenImageInfo(recommen, "1");
			groupTypeId = "1";
		}else if("5-1".equals(displayType)||"5-2".equals(displayType)){  //图片
			resturnPage = rootPage+"recommenFormImageGroup";
			groupTypeId = "1";
		}else if("6".equals(displayType)){ //装备
			resturnPage = rootPage+"recommenFormEquipment";
			RecommenUtils.setRecommenImageInfo(recommen, "1");
		}else{
			resturnPage = rootPage+"recommenForm";
		}
		grouptype.setId(groupTypeId);
		recommen.setGrouptype(grouptype ); //设置分组类型
		if("1".equals(groupTypeId)){ //类型为分组
			if(!StringUtils.isEmpty(recommen.getCode())){
				String parentCode = recommen.getCode();
				Recommen rec = new Recommen();
				rec.setCode(parentCode+"-");
				List<Recommen> list = recommenService.findList(rec);
				recommen.getRecommenList().addAll(list);
			}
		}
		
		if(StringUtils.isEmpty(recommen.getCode())){ //设置编码
			String code = DBSquence.nextId();
			recommen.setCode(code);
		}
		model.addAttribute("recommen", recommen);
		model.addAttribute("returnPage", resturnPage);
		model.addAttribute("opt",request.getParameter("opt"));
		return resturnPage;
	}
	
	@RequiresPermissions("cms:recommen:edit")
	@RequestMapping(value = "formChild")
	public String  formChild(Recommen recommen,String parentCode,HttpServletRequest request, HttpServletResponse response, Model model) throws UnsupportedEncodingException {
		
		//修改操作
		if(recommen!=null&&recommen.getRecommenList()!=null&&recommen.getRecommenList().size()>0){
			int len = recommen.getRecommenList().size();
			recommen = recommen.getRecommenList().get(len-1);
		}
		if(recommen == null){
			recommen = new Recommen();
		}
		
		if(StringUtils.isEmpty(recommen.getCode())){
			String code = parentCode+'-'+(int)(Math.random()*100000);
			recommen.setCode(code);
		}
		
		//发布状态
		if(recommen.getIspublish()==null){
			Dict ispublish = new Dict();
			recommen.setIspublish(ispublish);
		}
		if(StringUtils.isEmpty(recommen.getIspublish().getId())){
			recommen.getIspublish().setId("0");
		}
		
		//小标位置
		if(recommen.getInfoposition()==null){
			Dict infoposition = new Dict();
			recommen.setInfoposition(infoposition);
		}
		if(StringUtils.isEmpty(recommen.getInfoposition().getId())){
			recommen.getInfoposition().setId("0");
		}
		
		
		//推荐类型
		if(recommen.getRescomtype()==null){
			Dict rescomtype = new Dict();
			recommen.setRescomtype(rescomtype);
			if(StringUtils.isEmpty(recommen.getRescomtype().getId())){
				rescomtype.setId("0");
			}
		}
		
		//缩放图
		if(recommen.getImageinfoList().size()==0){
			List<Dict> dicts = DictUtils.getDictList("imagetype");
			for (Dict dict : dicts) {
				Imageinfo imageinfo = new Imageinfo();
				Dict dict1 = new Dict();
				dict1.setId(dict.getValue());
				imageinfo.setImagetype(dict1);
				recommen.getImageinfoList().add(imageinfo);
			}
		}
		
		model.addAttribute("recommen", recommen);
		
		return "modules/cms/recommen/recommenFormChild";
	}
	
	@RequiresPermissions("cms:recommen:edit")
	@RequestMapping(value = "save")
	public String save(Recommen recommen, Model model,HttpServletRequest request, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, recommen)){
			return form(recommen, model);
		}
		recommenService.save(recommen);
		model.addAttribute("recommen", recommen);
		model.addAttribute("opt","save");
		model.addAttribute("message","保存推荐成功");
		String returnPage = request.getParameter("returnPage");
		model.addAttribute("returnPage", returnPage);
		return returnPage;
	}
	
	@RequiresPermissions("cms:recommen:edit")
	@RequestMapping(value = "delete")
	public String delete(Recommen recommen, RedirectAttributes redirectAttributes) {
		recommenService.delete(recommen);
		addMessage(redirectAttributes, "删除推荐成功");
		return "redirect:"+Global.getAdminPath()+"/cms/recommen/?repage";
	}

	@RequiresPermissions("cms:recommen:edit")
	@RequestMapping(value = "batchDelete")
	public String delete(String ids, RedirectAttributes redirectAttributes) {
		recommenService.delete(ids);
		addMessage(redirectAttributes, "删除推荐成功");
		return "redirect:"+Global.getAdminPath()+"/cms/recommen/?repage";
	}
	
	/**
	 * 批量修改排序
	 */
	@RequiresPermissions("cms:recommen:edit")
	@RequestMapping(value = "updateSort")
	public String updateSort(String[] ids, Integer[] sorts, RedirectAttributes redirectAttributes) {
    	int len = ids.length;
    	Recommen[] entitys = new Recommen[len];
    	for (int i = 0; i < len; i++) {
    		entitys[i] = recommenService.get(ids[i]);
    		entitys[i].setSort(sorts[i]);
    		recommenService.save(entitys[i]);
    	}
    	addMessage(redirectAttributes, "更新顺序成功");
		return "redirect:"+Global.getAdminPath()+"/cms/recommen/?repage";
	}
}